<?php
namespace control;
// SMSConfigClass
class SMSConfigClass extends adIndexClass
{
	private const title    = '短信设置';
	private const page     = 'SMSConfig';
	private const table    = 'sms_template';
	private const workflow  = ['草稿', '审核中', '已通过', '未通过'];
	
	/**
	 * 查询表单
	 *
	 * @param string $workFlow
	 * @return string
	 */
	public function homeForm(string $workFlow): string
	{
		if ($workFlow == '签名设置') {
			$html = text(["name" => "name", "title" => "签名名称"]);
		} else {
			$html = text(["name" => "name", "title" => "模板名称"]) .
			        text(["name" => "body", "title" => "短信内容"]) .
			        text(["name" => "text", "title" => "模板备注"]) .
			        select(["name" => "state", "title" => "模板状态", 'option' => ['启用', '停用']]);
		}
		$html .=
			select(["name" => "workFlow", "title" => "审核状态", 'option' => self::workFlow]) .
			text([
				'name' => 'commitTime', 'title' => '申请时间 ~ 申请时间
        ', 'class' => 'text width200', 'laydate' => ['range' => '~', 'type' => 'date'],
			]);
		return $this->search($html, 'menu');
	}
	
	/**
	 * 查询条件
	 *
	 * @param string $workFlow
	 * @return string
	 */
	public function home($workFlow = '签名设置'): string
	{
		$data         = [
			"id"   => "all",
			"menu" => [
				"home"     => "签名设置",
				"template" => '模板设置',
			],
		];
		$data['html'] = $this->homeForm($workFlow);
		return $this->tab($data);
	}
	
	/*社保数据-列表页-查询结果*/
	public function homeSearch()
	{
		$where = ' category = \'签名\' ';
		$equal = [
			'workFlow' => $this->post('workFlow'),
		];
		$like  = [
			'name' => $this->post('name'),
		];
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'date', 'commitTime');
		}
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		$page  = $this->page(["table" => self::table, "where" => $where, "order" => " time desc"]);
		
		//获取表头
		$checkAll = $this->checkAll("listForm", "listId");
		$tr[]     = [$checkAll, '签名名称', '审核状态', '原因', '申请人', '申请时间', '审核时间'];
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"  => [
					"name" => "listId", "value" => $array['id'],
				],
				"edit" => [
					"title" => "编辑", "click" => "layer('{$this->get('cla')}', 'editPage', {'id': '{$array['id']}' })",
				],
			];
			//本行
			$tr[] = [$this->dominate($dominate), $array['name'], $array['workFlow'], $array['text'], self::findStaff($array['stid']), $array['commitTime'], $array['passTime']];
		}
		//控件
		$button = "";
		if ($this->power(self::page, "edit")) {
			$button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'editPage', {'id': '" . self::getId() . "' })\">新增</span>\n";
		}
		if ($this->power(self::page, "del")) {
			$button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del', category:'签名' })\">删除</span>\n";
		}
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(["tr" => $tr]) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}
	
	public function editPage()
	{
		$info = query(self::table, " id = '" . $this->post('id') . "' ");
		$html = $this->layerEdit([
			"table" => [
				[
					'签名名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
				],
			],
		]);
		return $this->layer(["title" => "编辑" . self::title, "height" => 150, "width" => 800, "html" => $html]);
	}
	
	/*成本表基本资料新增或修改-异步处理*/
	public function editPageEdit()
	{
		$id         = $this->post('id') ? $this->post('id') : self::getNo();
		$field      = [
			'name' => $this->post('name'),
		];
		$annotation = [
			'name' => '签名名称',
		];
		$rules      = [
			'name' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (sqlNum(self::table, " name = '{$field['name']}' AND id <> '$id'   ") > 0) {
				$json['warn'] = "已存在相同签名【{$field['name']}】";
				goto resp;
			}
			if (static::isNull($info['id'])) {
				$field        = array_merge($field, [
					'id'       => $id,
					'category' => '签名',
					'stid'     => self::$stid,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&pid=" . $id;
			}
		}
		
		resp:
		return json_encode($json, 320);
	}
	
	public function template()
	{
		$json['html'] = $this->homeForm('模板');
		return json_encode($json, 320);
	}
	
	public function templateSearch()
	{
		//查询结果
		$where = ' category = \'模板\' ';
		$equal = [
			'state'    => $this->post('state'),
			'workFlow' => $this->post('workFlow'),
		];
		$like  = [
			'name' => $this->post('name'),
			'body' => $this->post('body'),
			'text' => $this->post('text'),
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'date', 'commitTime');
		}
		$page = $this->page(["table" => self::table, "where" => $where, "order" => " time desc"]);
		
		//获取表头
		$checkAll = $this->checkAll("listForm", "listId");
		$tr[]     = [$checkAll, '模板名称', '模板内容', '短信类型', '模板备注', '模板状态', '审核状态', '申请人', '申请时间', '审核时间'];
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"  => [
					"name" => "listId", "value" => $array['id'],
				],
				"edit" => [
					"title" => "编辑", "click" => "layer('{$this->get('cla')}', 'editTemplate', {'id': '{$array['id']}' })",
				],
			];
			//本行
			$tr[] = [$this->dominate($dominate), $array['name'], $array['body'], $array['type'], $array['text'], $array['state'], $array['workFlow'], self::findStaff($array['stid']), $array['commitTime'], $array['passTime']];
		}
		//控件
		$button = "";
		if ($this->power(self::page, "edit")) {
			$button .= "<span onclick=\"layer('{$this->get('cla')}', 'editTemplate', {'id': '" . self::getId() . "' })\" class='spanButton'>新增</span>\n";
		}
		if ($this->power(self::page, "del")) {
			$button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del', category:'模板' })\">删除</span>\n";
		}
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(["tr" => $tr]) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}
	
	public function editTemplate()
	{
		$info = query(self::table, " id = '" . $this->post('id') . "' ");
		$html = $this->layerEdit([
			"table" => [
				[
					must . '模板名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
				],
				[
					must . '模板内容' => textarea(['name' => "body", 'class' => 'text', 'title' => '可添加前面变量等,例:  【雨木科技】{1}是您的登陆验证码, 请于{2}分钟内填写,如非本人操作,请忽略本短信。', 'value' => $info['body']]),
				],
				[
					'短信类型' => radio(['name' => "type", 'class' => 'text', 'value' => ['普通短信', '营销短信'], 'checked' => $info['type'],]),
				],
				[
					must . '备注' => textarea(['name' => "text", 'title' => '模板备注,例如申请原因,使用场景等', 'class' => 'text', 'value' => $info['text']]),
				],
			
			],
		]);
		return $this->layer(["title" => "编辑" . self::title, "height" => 450, "width" => 800, "html" => $html]);
	}
	
	/*成本表基本资料新增或修改-异步处理*/
	public function editTemplateEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'name' => $this->post('name'),
			'body' => $this->post('body'),
			'type' => $this->post('type'),
			'text' => $this->post('text'),
		];
		$annotation = [
			'name' => '模板名称',
			'body' => '模板内容',
			'type' => '短信类型',
			'text' => '模板备注',
		];
		$rules      = [
			'name' => 'required',
			'body' => 'required',
			'type' => 'required',
			'text' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (sqlNum(self::table, " name = '{$field['name']}' AND id <> '$id'   ") > 0) {
				$json['warn'] = "已存在相同模板名称【{$field['name']}】";
				goto resp;
			}
			if (static::isNull($info['id'])) {
				$field        = array_merge($field, [
					'id'       => $id,
					'category' => '模板',
					'stid'     => self::$stid,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
			}
		}
		
		resp:
		return json_encode($json, 320);
	}
	
	
	// 操作中转
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = $word = false; // 需要密码
		$form   = $power = $title = '';
		$append = [];
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = 'SMSConfigDelete';
				$function = 'isDelete';
				$form     = self::page . 'OperateForm, listForm';
				$append[] = hidden(['name' => 'category', 'value' => $this->post('category')]);
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home&menu=template',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'append'   => $append,
				'word'     => $word,
			]);
		}
		
		resp:
		return json_encode($json, 320);
	}
	
	
	// 确认删除信息
	public function isDelete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 判断field
			$fieldKey   = 'state';
			$fieldVlaue = '启用';
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info[$fieldKey] == $fieldVlaue) {
						$text .= self::title . "【{$info['id']}】为{$fieldVlaue}状态，无法删除<br>";
						continue;
					}
					// 删除表
					delete([
						"table" => self::table,
						"where" => $where,
					]);
					//添加记录
					$text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . (isset($info['name']) ? "，名称【{$info['name']}】" : '') . '<br>';
					$x++;
				}
			}
			
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		
		resp:
		return json_encode($json, 320);
	}
}
